# ================================================#
#             Replication files for:              #
#   "The Legacy of Multi-Dimensional Conflict"    #
#         Joan Barceló and Leonid Peisakhin       #
#          Comparative Political Studies          #
#          Last updated: August 29, 2025          #
# ================================================#

# ------------------
# INDIVIDUAL ANALYSIS: 
# Replication script to reproduce Table 3, 4, and Figure 3 in the main text of the manuscript.
# Replication script to reproduce Appendices C.2, F, H.2, L.2, L.4, M, N, O.2, O.4, P.2, Q.1, Q.3, R.2, R.3.
# ------------------

# Replication files prepared using: "R version 4.2.3 (2023-03-15)"#

# ------------------
# Load packages
# ------------------

library(estimatr)      
library(modelsummary)
library(dplyr)
library(tidyr)
library(stringr)
library(kableExtra)
library(ggplot2)
library(estimatr)
library(broom)
library(ivreg)

# ------------------
# Load data
# ------------------

PATH <- ''

individual_data <- 
  readstata13::read.dta13(paste0(PATH, "survey_data.dta"))

conjoint_data <- 
  readstata13::read.dta13(paste0(PATH, "conjoint_data.dta"))

# ------------------#
# ------------------#
#      Table 3      #
# ------------------#
# ------------------#

starify <- function(p) {
  if (is.na(p)) "" else if (p < .01) "**" else if (p < .05) "*" else if (p < .10) "+" else ""
}

west_east_t <- function(x, east_flag = individual_data$east_river) {
  ok <- !is.na(x) & !is.na(east_flag)
  x <- x[ok]
  east_flag <- east_flag[ok]
  
  west <- mean(x[east_flag == 0], na.rm = TRUE)
  east <- mean(x[east_flag == 1], na.rm = TRUE)
  
  tt   <- suppressWarnings(t.test(x ~ east_flag))
  tval <- abs(as.numeric(tt$statistic))
  pval <- as.numeric(tt$p.value)
  
  tibble::tibble(
    West  = round(west * 100, 1),
    East  = round(east * 100, 1),
    tstat = paste0(format(round(tval, 2), nsmall = 2), starify(pval))
  )
}

rows <- list(
  "Death of relatives" = list(all = individual_data$deaths,           nat = individual_data$deaths_nat,           rep = individual_data$deaths_rep),
  "Fleeing home"       = list(all = individual_data$leaving,          nat = individual_data$leaving_nat,          rep = individual_data$leaving_rep),
  "Imprisonment"       = list(all = individual_data$imprisonment,     nat = individual_data$imprisonment_nat,     rep = individual_data$imprisonment_rep),
  "Bodily harm"        = list(all = individual_data$bodilyharm,       nat = individual_data$bodilyharm_nat,       rep = individual_data$bodilyharm_rep),
  "Property damage"    = list(all = individual_data$materialdamage,   nat = individual_data$materialdamage_nat,   rep = individual_data$materialdamage_rep)
)

Table3 <- purrr::imap_dfr(
  rows,
  function(vars, label) {
    c_all <- west_east_t(vars$all)
    c_nat <- west_east_t(vars$nat)
    c_rep <- west_east_t(vars$rep)
    tibble(
      Outcome = label,
      `All violence, West` = c_all$West,
      `All violence, East` = c_all$East,
      `All violence, t-stat` = c_all$tstat,
      `Nationalist violence, West` = c_nat$West,
      `Nationalist violence, East` = c_nat$East,
      `Nationalist violence, t-stat` = c_nat$tstat,
      `Republican violence, West` = c_rep$West,
      `Republican violence, East` = c_rep$East,
      `Republican violence, t-stat` = c_rep$tstat
    )
  }
)

print(Table3)

# ------------------#
# ------------------#
#      Table 4      #
# ------------------#
# ------------------#

t4m1_se <- lm_robust(
  vote_leftist ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data, clusters = municipality, se_type = "stata"
)

t4m2_se <- lm_robust(
  leftparty_closeness ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data, clusters = municipality, se_type = "stata"
)

t4m3_se <- lm_robust(
  left_scale ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data, clusters = municipality, se_type = "stata"
)

t4m4_se <- lm_robust(
  vote_catalan ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data, clusters = municipality, se_type = "stata"
)

t4m5_se <- lm_robust(
  catparty_closeness ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data, clusters = municipality, se_type = "stata"
)

t4m6_se <- lm_robust(
  proindy_protest ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data, clusters = municipality, se_type = "stata"
)

models <- list(
  "Voting for leftist parties"                 = t4m1_se,
  "Proximity to leftist parties"               = t4m2_se,
  "Left-right scale"                           = t4m3_se,
  "Voting for Catalan nationalist parties"     = t4m4_se,
  "Proximity to Catalan nationalist parties"   = t4m5_se,
  "Catalan nationalist protest behavior"       = t4m6_se
)

omit_everything_but_east <- "^(?!east_river$).*"

gmap <- data.frame(
  raw   = "nobs",
  clean = "Observations",
  fmt   = 0,
  omit  = FALSE
)

Table4 <- modelsummary(
  models,
  coef_map  = c("east_river" = "East of the river"),
  coef_omit = omit_everything_but_east,
  estimate  = "{estimate}{stars}",
  statistic = "({std.error})",
  gof_map   = gmap,
  stars     = c("**" = .01, "*" = .05, "+" = .10),
  booktabs  = TRUE,
  fmt = 2,
  notes = list(
    "+ p<0.1; * p<0.05; ** p<0.01. Higher values indicate stronger support for the Left in columns 1, 2, and 3, and for Catalan nationalism in columns 4, 5, and 6. Control variables include gender, age, age squared, a factored index of property ownership, and relatives prewar occupations. Standard errors are clustered at the municipality level. There are fewer observations for the voting outcome because of non-reports. There is also missingness on ancestors pre-war occupations. Appendix M shows that the results are robust to different sets of controls. Appendix H presents additional models incorporating all available aggregate and individual-level prewar covariates."
  )
)

print(Table4)

# ------------------#
# ------------------#
#   Text on p. 29   #
# ------------------#
# ------------------#

tt_residence <- with(
  individual_data,
  t.test(
    family_resided_town_war[east_river == 0],
    family_resided_town_war[east_river == 1],
    alternative = "two.sided",
    var.equal = FALSE
  )
)

west_mean <- mean(individual_data$family_resided_town_war[individual_data$east_river == 0], na.rm = TRUE)
east_mean <- mean(individual_data$family_resided_town_war[individual_data$east_river == 1], na.rm = TRUE)
stars <- ifelse(tt_residence$p.value < 0.01, "**",
                ifelse(tt_residence$p.value < 0.05, "*",
                       ifelse(tt_residence$p.value < 0.10, "+", "")))

sprintf(
  "West mean = %.1f, East mean = %.1f, t = %.3f%s, p = %.2f",
  round(west_mean*100, 1), round(east_mean*100,1), unname(abs(tt_residence$statistic)), stars, tt_residence$p.value
)


# ------------------#
# ------------------#
#      Figure 3     #
# ------------------#
# ------------------#

conjoint_results <- lm_robust(out ~ as.factor(catalan_name) + as.factor(age) + as.factor(edu) + as.factor(birth) + as.factor(econ) + as.factor(terri),
                              data=conjoint_data, clusters=id, se_type="stata")

tidy_results <- tidy(conjoint_results)

new_row <- data.frame(
  term = c("Barcelona", "Birthplace province:",  "Illiterate (ref.)", "Education:", "Age:", "23 (ref.)", 
           "Center−periphery \n preferences:", "Unionist (ref.)", "Left-Right preferences:", "Conservative (ref.)", 
           "Name origin:", "spanish_name (ref.)", "Space1", "Space2", "Space3", "Space4", "Space5", "Space6"),
  estimate = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  std.error = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  statistic = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  p.value = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  conf.low = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  conf.high = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  df = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  outcome = c("out", "out", "out", 'out', "out", 'out', "out", "out", "out", "out", "out", "out", "out", "out", "out", "out", "out", "out")
)

tidy_results <- rbind(new_row, tidy_results)

label_map <- c(
  "Left-Right preferences:" = "Left-right preferences:",
  "Conservative (ref.)" = "Conservative (ref.)",
  "as.factor(econ)2" = "Socialist",
  "Center−periphery \n preferences:" = "Center−periphery preferences:",
  "Unionist (ref.)" = "Unionist (ref.)",
  "as.factor(terri)2" = "Separatist",
  "Name origin:" = "Name origin:",
  "spanish_name (ref.)" = "Spanish name (ref.)",
  "as.factor(catalan_name)1" = "Catalan name",
  "Age:" = "Age:",
  "23 (ref.)" = "23 (ref.)",
  "as.factor(age)27" = "27",
  "as.factor(age)30" = "30",
  "as.factor(age)32" = "32",
  "as.factor(age)34" = "34",
  "as.factor(age)39" = "39",
  "as.factor(age)45" = "45",
  "Education:" = "Education:",
  "Illiterate (ref.)" = "Illiterate (ref.)", 
  "as.factor(edu)2" = "Primary school",
  "as.factor(edu)3" = "Secondary school",
  "as.factor(edu)4" = "College degree",
  "Birthplace province:" = "Birthplace province:",
  "Barcelona" = "Barcelona (ref.)",
  "as.factor(birth)1" = "Girona",
  "as.factor(birth)3" = "Tarragona",
  "as.factor(birth)4" = "Lleida",
  "Space1" = " ",
  "Space2" = "  ", 
  "Space3" = "   ", 
  "Space4" = "    ", 
  "Space5" = "     ", 
  "Space6" = "      "
)

tidy_results$term <- label_map[tidy_results$term]

attribute_order <- c("Lleida", "Girona", "Tarragona", "Barcelona (ref.)", 
                     "Birthplace province:", " ", 
                     "College degree", "Secondary school", "Primary school", "Illiterate (ref.)",
                     "Education:", "  ", 
                     "45", "39", "34", "32", "30", "27", "23 (ref.)",
                     "Age:", "   ", 
                     "Catalan name", "Spanish name (ref.)",
                     "Name origin:", "    ", 
                     "Separatist", "Unionist (ref.)",
                     "Center−periphery preferences:", "     ", 
                     "Socialist", "Conservative (ref.)",
                     "Left-right preferences:", "      ")


bold_labels <- function(labels) {
  target_labels <- c("Name origin:", "Left-right preferences:", "Center−periphery preferences:", "Age:", "Education:", "Birthplace province:")
  lapply(labels, function(label) {
    if (label %in% target_labels) {
      return(paste0("<b>", label, "</b>"))
    } else {
      return(label)
    }
  })
}

Figure3 <- ggplot(tidy_results, aes(x = factor(term, levels = attribute_order), y = estimate)) +
  geom_point(aes(
    color = case_when(
      term %in% c("Conservative (ref.)", "Socialist") ~ "salmon",
      term %in% c("Unionist (ref.)", "Separatist") ~ "lightblue",
      term %in% c("Catalan name", "Spanish name (ref.)") ~ "red",
      term %in% c("23 (ref.)", "27", "30", "32", "34", "39", "45") ~ "white",
      term %in% c("Illiterate (ref.)", "Primary school", "Secondary school", "College degree") ~ "darkgreen",
      term %in% c("Barcelona (ref.)", "Girona", "Tarragona", "Lleida") ~ "lightgreen",
      term %in% c("Name origin:", "Left-right preferences:", "Center−periphery preferences:", "Age:", "Education:", "Birthplace province:") ~ "pink",
      TRUE ~ "black"
    ),
    alpha = case_when(
      term %in% c("Name origin:", "Left-right preferences:", "Center−periphery preferences:", "Age:", "Education:", "Birthplace province:") ~ 0.1,
      TRUE ~ 1
    )
  ), size = 3) +
  scale_x_discrete(labels = c("Lleida", "Girona", "Tarragona", "Barcelona (ref.)", 
                              expression(bold("Birthplace province:")), " ", 
                              "College degree", "Secondary school", "Primary school", "Illiterate (ref.)",
                              expression(bold("Education:")), "  ", 
                              "45", "39", "34", "32", "30", "27", "23 (ref.)",
                              expression(bold("Age:")), "   ", 
                              "Catalan name", "Spanish name (ref.)",
                              expression(bold("Name origin:")), "    ", 
                              "Separatist", "Unionist (ref.)",
                              expression(bold("Center−periphery preferences:")), "     ", 
                              "Socialist", "Conservative (ref.)",
                              expression(bold("Left-right preferences:")))) +
  geom_errorbar(aes(ymin = estimate - 1.96 * std.error, ymax = estimate + 1.96 * std.error, 
                    color = case_when(
                      term %in% c("Conservative (ref.)", "Socialist") ~ "salmon",
                      term %in% c("Unionist (ref.)", "Separatist") ~ "lightblue",
                      term %in% c("Catalan name", "Spanish name (ref.)") ~ "red",
                      term %in% c("23 (ref.)", "27", "30", "32", "34", "39", "45") ~ "white",
                      term %in% c("Illiterate (ref.)", "Primary school", "Secondary school", "College degree") ~ "darkgreen",
                      term %in% c("Barcelona (ref.)", "Girona", "Tarragona", "Lleida") ~ "lightgreen",
                      term %in% c("Name origin:", "Left-right preferences:", "Center−periphery preferences:", "Age:", "Education:", "Birthplace province:") ~ "pink",
                      TRUE ~ "black"
                    )), width = 0.2, size = 1) +
  coord_flip() +
  ylim(-0.10, 0.30) +
  geom_hline(yintercept = 0, alpha = 0.5, color = "gray90", linetype = "solid") + 
  theme_minimal() +
  theme(
    axis.title = element_text(size = 16),
    axis.text = element_text(size = 14),
    legend.title = element_text(size = 14),
    legend.text = element_text(size = 12)
  ) +
  theme(
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank(),  
    panel.background = element_blank(),
    axis.title.x = element_text(face = "bold")
  )  + 
  labs(x = "", y = "Effect on Pr(Combatant of the Republican Army)", title = "") +
  scale_color_manual(values = c("white", "lightblue", "blue", "lightgreen", "white", "wheat", "red", "pink")) + 
  guides(color = "none", alpha = "none")

print(Figure3)



# ---------------------------------- #
# ---------------------------------- #
# ---------------------------------- #
#      SUPPLEMENTARY INFORMATION     #
# ---------------------------------- #
# ---------------------------------- #
# ---------------------------------- #

# --------------------------- #
# --------------------------- #
#  APPENDIX C: TABLE C.1      #
# --------------------------- #
# --------------------------- #

m1 <- lm_robust(
  fam_supp_nat_vs_rep ~ I(prewar_much_land + prewar_orchard) +
    I(prewar_many_animals + prewar_horses),
  data = individual_data,
  clusters = municipality,
  se_type = "stata"
)

m2 <- lm_robust(
  fam_supp_nat_vs_rep ~ association_catalan_per1000,
  data = individual_data,
  clusters = municipality,
  se_type = "stata"
)

m3 <- lm_robust(
  fam_supp_nat_vs_rep ~ association_right_per1000,
  data = individual_data,
  clusters = municipality,
  se_type = "stata"
)

var_labels <- c(
  "I(prewar_much_land + prewar_orchard)"    = "Land or Orchards (prewar family ownership)",
  "I(prewar_many_animals + prewar_horses)"  = "Animals or Horses (prewar family ownership)",
  "association_catalan_per1000"       = "Catalanist associations pre-1936 (per 1,000)",
  "association_right_per1000"         = "Conservative associations pre-1936 (per 1,000)",
  "(Intercept)"                       = "Constant"
)

TableC1 <- modelsummary(
  list("Model 1" = m1, "Model 2" = m2, "Model 3" = m3),
  coef_map = var_labels,
  gof_map = c("nobs", "F"),
  statistic = "({std.error})",
  stars = c("+" = .10, "*" = .05, "**" = .01),
  title = "Table C.1: Predictors of Family Support for Nationalists vs Republicans",
  notes = "Note: +p<0.1; *p<0.05; **p<0.01. Standard errors are clustered at the municipality level."
)

print(TableC1)

# --------------------------- #
# --------------------------- #
#         APPENDIX F          #
# --------------------------- #
# --------------------------- #

rows_nm <- list(
  "Death of relatives" = list(all = individual_data$deaths_nm,         nat = individual_data$deaths_nat_nm,         rep = individual_data$deaths_rep_nm),
  "Bodily harm"        = list(all = individual_data$bodilyharm_nm,     nat = individual_data$bodilyharm_nat_nm,     rep = individual_data$bodilyharm_rep_nm),
  "Imprisonment"       = list(all = individual_data$imprisonment_nm,   nat = individual_data$imprisonment_nat_nm,   rep = individual_data$imprisonment_rep_nm),
  "Property damage"    = list(all = individual_data$materialdamage_nm, nat = individual_data$materialdamage_nat_nm, rep = individual_data$materialdamage_rep_nm),
  "Fleeing home"       = list(all = individual_data$leaving_nm,        nat = individual_data$leaving_nat_nm,        rep = individual_data$leaving_rep_nm)
)

TableF1 <- purrr::imap_dfr(
  rows_nm,
  function(vars, label) {
    c_all <- west_east_t(vars$all, individual_data$east_river)
    c_nat <- west_east_t(vars$nat, individual_data$east_river)
    c_rep <- west_east_t(vars$rep, individual_data$east_river)
    tibble(
      Outcome = label,
      `All violence, West` = c_all$West,
      `All violence, East` = c_all$East,
      `All violence, t-stat` = c_all$tstat,
      `Nationalist violence, West` = c_nat$West,
      `Nationalist violence, East` = c_nat$East,
      `Nationalist violence, t-stat` = c_nat$tstat,
      `Republican violence, West` = c_rep$West,
      `Republican violence, East` = c_rep$East,
      `Republican violence, t-stat` = c_rep$tstat
    )
  }
)

N_tab <- with(individual_data, sum(!(is.na(deaths_nm) & is.na(bodilyharm_nm) & is.na(imprisonment_nm) &
                                              is.na(materialdamage_nm) & is.na(leaving_nm))))

print(TableF1)

kbl(TableF1, format = "html", align = "lccccccccc") |>
  add_header_above(c(" " = 1,
                     "All violence" = 3,
                     "Nationalist violence" = 3,
                     "Republican violence" = 3)) |>
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover")) |>
  footnote(
    general = paste0(
      "+ p<0.1; * p<0.05; ** p<0.01. ",
      "p-values are based on two-tailed t-tests comparing east-west differences. ",
      "N = ", format(N_tab, big.mark = ","), 
      ". Respondents who do not know their family suffering are omitted from this table."
    )
  )


# --------------------------- #
# --------------------------- #
#         APPENDIX H          #
# --------------------------- #
# --------------------------- #

# --------------------------- #
#   APPENDIX H.2 / TABLE H.1  #
# --------------------------- #

rhs <- paste(
  "east_river + female + age + age2 + properties_score + prewar_family_politician", 
  "+ prewar_family_civilservent + prewar_family_armyofficer +", 
  "prewar_family_priest + prewar_family_tradeunionleader +",
  "exec_by_left_prefront_per1000 + burned_churches_per1000 + looted_churches_36_37_per1000 +",
  "undeter_damage_churches_per1000 + priests_killed_per1000 +",
  "population_hecho_1920 + population_hecho_1930 +",
  "association_left_per1000 + association_catalan_per1000 +",
  "as.numeric(cntaffiliation) + as.numeric(ugtaffiliation) +",
  "as.numeric(spnxleft_1931) + as.numeric(spnxright_1931) +",
  "as.numeric(catxleft_1931) + as.numeric(catxright_1931) + as.numeric(turnout_1931) +",
  "as.numeric(catxleft_1932) + as.numeric(catxright_1932) + as.numeric(spnxleft_1932) +",
  "as.numeric(turnout_1932) +",
  "as.numeric(spnxleft_1933) + as.numeric(spnxright_1933) +",
  "as.numeric(catxleft_1933) + as.numeric(catxright_1933) + as.numeric(turnout_1933) +",
  "as.numeric(catxleft_1936) + as.numeric(catxright_1936) +",
  "as.numeric(spnxleft_1936) + as.numeric(turnout_1936)"
)

outs <- list(
  "Voting for leftist parties"               = "vote_leftist",
  "Proximity to leftist parties"             = "leftparty_closeness",
  "Left-right scale"                         = "left_scale",
  "Voting for Catalan nationalist parties"   = "vote_catalan",
  "Proximity to Catalan nationalist parties" = "catparty_closeness",
  "Nationalist protest behavior"             = "proindy_protest"
)

mods <- lapply(outs, function(y) {
  f <- as.formula(paste(y, "~", rhs))
  lm_robust(f,
            data = individual_data,
            clusters = municipality,
            se_type = "stata")
})

lab <- c(
  "east_river"                                        = "East of the river",
  "female"                                            = "Female",
  "age"                                               = "Age",
  "age2"                                              = "Age squared",
  "properties_score"                                  = "Prewar property ownership",
  "prewar_family_politician"                          = "Politician",
  "prewar_family_civilservent"                        = "Civil servant",
  "prewar_family_armyofficer"                         = "Army officer",
  "prewar_family_priest"                              = "Priest",
  "prewar_family_tradeunionleader"                    = "Trade union leader",
  "exec_by_left_prefront_per1000"                     = "Executions by the left^a",
  "burned_churches_per1000"                           = "Church arson^a",
  "looted_churches_36_37_per1000"                     = "Looted churches^a",
  "undeter_damage_churches_per1000"                   = "Other church damage^a",
  "priests_killed_per1000"                            = "Number of priests murdered^a",
  "population_hecho_1920"                             = "Population 1920",
  "population_hecho_1930"                             = "Population 1930",
  "association_left_per1000"                          = "Leftist associations^a",
  "association_catalan_per1000"                       = "Catalan associations^a",
  "as.numeric(cntaffiliation)"                        = "% CNT affiliation",
  "as.numeric(ugtaffiliation)"                        = "% UGT affiliation",
  "as.numeric(spnxleft_1931)"                         = "% Vote for Spanish left, 1931",
  "as.numeric(spnxright_1931)"                        = "% Vote for Spanish right, 1931",
  "as.numeric(catxleft_1931)"                         = "% Vote for Catalan left, 1931",
  "as.numeric(catxright_1931)"                        = "% Vote for Catalan right, 1931",
  "as.numeric(turnout_1931)"                          = "Turnout 1931",
  "as.numeric(catxleft_1932)"                         = "% Vote for Catalan left, 1932",
  "as.numeric(catxright_1932)"                        = "% Vote for Catalan right, 1932",
  "as.numeric(spnxleft_1932)"                         = "% Vote for Spanish left, 1932",
  "as.numeric(turnout_1932)"                          = "Turnout 1932",
  "as.numeric(spnxleft_1933)"                         = "% Vote for Spanish left, 1933",
  "as.numeric(spnxright_1933)"                        = "% Vote for Spanish right, 1933",
  "as.numeric(catxleft_1933)"                         = "% Vote for Catalan left, 1933",
  "as.numeric(catxright_1933)"                        = "% Vote for Catalan right, 1933",
  "as.numeric(turnout_1933)"                          = "Turnout 1933",
  "as.numeric(catxleft_1936)"                         = "% Vote for Catalan left, 1936",
  "as.numeric(catxright_1936)"                        = "% Vote for Catalan right, 1936",
  "as.numeric(spnxleft_1936)"                         = "% Vote for Spanish left, 1936",
  "as.numeric(turnout_1936)"                          = "Turnout 1936",
  "(Intercept)"                                       = "Constant"
)

row_order <- names(lab)

gmap <- data.frame(raw = "nobs", clean = "Observations", fmt = 0, omit = FALSE)

TableH1 <- modelsummary(
  mods,
  coef_map  = lab,
  coef_omit = "^\\(Intercept\\)$",
  estimate  = "{estimate}{stars}",
  statistic = "({std.error})",
  gof_map   = gmap,
  stars     = c("**" = .01, "*" = .05, "+" = .10),
  fmt       = 2,
  booktabs  = TRUE
)

attr(TableH1, "df")$header <- c(
  "", names(outs)
)

print(TableH1)

# --------------------------- #
# --------------------------- #
#         APPENDIX L          #
# --------------------------- #
# --------------------------- #

# --------------------------- #
#   APPENDIX L.2: TABLE L.1   #
# --------------------------- #

iv_formula_rhs <- paste(
  "violence_nat + violence_rep +",
  "female + age + age2 +",
  "properties_score +",
  "prewar_family_politician + prewar_family_civilservent +",
  "prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader"
)

make_iv <- function(y, data) {
  f_iv <- as.formula(
    paste(
      y, "~", iv_formula_rhs, "|",
      ".", "- violence_nat + east_river"
    )
  )
  ivreg(f_iv, data = data, na.action = na.omit)
}

mods_iv <- list(
  "Voting for leftist parties"               = make_iv("vote_leftist",            individual_data),
  "Proximity to leftist parties"             = make_iv("leftparty_closeness",     individual_data),
  "Left-right scale"                         = make_iv("left_scale",              individual_data),
  "Voting for Catalan nationalist parties"   = make_iv("vote_catalan",            individual_data),
  "Proximity to Catalan nationalist parties" = make_iv("catparty_closeness",      individual_data),
  "Catalan nationalist protest behavior"     = make_iv("proindy_protest",         individual_data)
)


vc_list <- lapply(mods_iv, function(m) {
  idx <- as.integer(rownames(m$model))        
  cl  <- individual_data$municipality[idx]
  
  N   <- nobs(m)
  G   <- length(unique(cl))
  dfa <- (G / (G - 1)) * (N - 1) / df.residual(m)
  
  dfa * sandwich::vcovCL(m, cluster = cl, type = "HC0", adjust = TRUE)
})

coef_labels <- c(
  "violence_nat"                           = "Nationalist Violence (Index)\n(instrument = East of the river)",
  "violence_rep"                           = "Republican Violence (Index)",
  "female"                                 = "Female",
  "age"                                    = "Age",
  "age2"                                   = "Age squared",
  "properties_score"                       = "Prewar property ownership",
  "prewar_family_politician"               = "Politician",
  "prewar_family_civilservent"             = "Civil Servant",
  "prewar_family_armyofficer"              = "Army Officer",
  "prewar_family_priest"                   = "Priest",
  "prewar_family_tradeunionleader"         = "Trade Union Leader",
  "(Intercept)"                            = "Constant"
)

row_order <- c(
  "violence_nat", "violence_rep", "female",
  "age", "age2",
  "properties_score",
  "prewar_family_politician", "prewar_family_civilservent",
  "prewar_family_armyofficer", "prewar_family_priest",
  "prewar_family_tradeunionleader",
  "(Intercept)"
)

gmap <- data.frame(raw = "nobs", clean = "Observations", fmt = 0, omit = FALSE)

Table_L1_IV <- modelsummary(
  mods_iv,
  vcov      = vc_list,
  coef_map  = coef_labels,
  coef_omit = NULL,                
  statistic = "({std.error})",
  estimate  = "{estimate}{stars}",
  fmt       = 2,                  
  gof_map   = gmap,   
  booktabs = TRUE,
  stars     = c("**" = .01, "*" = .05, "+" = .10)
)

print(Table_L1_IV)

# --------------------------- #
#   APPENDIX L.4: TABLE L.2   #
# --------------------------- #

iv_formula_rhs_civ <- paste(
  "violence_nat_civ + violence_rep_civ +",
  "female + age + age2 +",
  "properties_score +",
  "prewar_family_politician + prewar_family_civilservent +",
  "prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader"
)

make_iv_civ <- function(y, data) {
  f_iv <- as.formula(
    paste(
      y, "~", iv_formula_rhs_civ, "|",
      ".", "- violence_nat_civ + east_river"
    )
  )
  ivreg(f_iv, data = data, na.action = na.omit)
}

mods_iv_civ <- list(
  "Voting for leftist parties"               = make_iv_civ("vote_leftist",            individual_data),
  "Proximity to leftist parties"             = make_iv_civ("leftparty_closeness",     individual_data),
  "Left-right scale"                         = make_iv_civ("left_scale",              individual_data),
  "Voting for Catalan nationalist parties"   = make_iv_civ("vote_catalan",            individual_data),
  "Proximity to Catalan nationalist parties" = make_iv_civ("catparty_closeness",      individual_data),
  "Catalan nationalist protest behavior"     = make_iv_civ("proindy_protest",         individual_data)
)


vc_list_civ <- lapply(mods_iv_civ, function(m) {
  idx <- as.integer(rownames(m$model))      
  cl  <- individual_data$municipality[idx]
  
  N   <- nobs(m)
  G   <- length(unique(cl))
  dfa <- (G / (G - 1)) * (N - 1) / df.residual(m)
  
  dfa * sandwich::vcovCL(m, cluster = cl, type = "HC0", adjust = TRUE)
})

coef_labels <- c(
  "violence_nat_civ"                       = "Nationalist Civilian Victimization\n(instrument = East of the river)",
  "violence_rep_civ"                       = "Republican Violence Victimization",
  "female"                                 = "Female",
  "age"                                    = "Age",
  "age2"                                   = "Age squared",
  "properties_score"                       = "Prewar property ownership",
  "prewar_family_politician"               = "Politician",
  "prewar_family_civilservent"             = "Civil Servant",
  "prewar_family_armyofficer"              = "Army Officer",
  "prewar_family_priest"                   = "Priest",
  "prewar_family_tradeunionleader"         = "Trade Union Leader",
  "(Intercept)"                            = "Constant"
)

row_order <- c(
  "violence_nat_civ", "violence_rep_civ", "female",
  "age", "age2",
  "properties_score",
  "prewar_family_politician", "prewar_family_civilservent",
  "prewar_family_armyofficer", "prewar_family_priest",
  "prewar_family_tradeunionleader",
  "(Intercept)"
)

gmap <- data.frame(raw = "nobs", clean = "Observations", fmt = 0, omit = FALSE)

Table_L2_IV_civ <- modelsummary(
  mods_iv_civ,
  vcov      = vc_list_civ,
  coef_map  = coef_labels,
  coef_omit = NULL,                
  statistic = "({std.error})",
  estimate  = "{estimate}{stars}",
  fmt       = 2,                  
  gof_map   = gmap,   
  booktabs = TRUE,
  stars     = c("**" = .01, "*" = .05, "+" = .10)
)

print(Table_L2_IV_civ)

# --------------------------- #
# --------------------------- #
#         APPENDIX M          #
# --------------------------- #
# --------------------------- #

ctrl_dem_prop <- ~ female + age + age2 + properties_score

ctrl_prewar <- ~ prewar_family_politician + prewar_family_civilservent +
  prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader

CL <- individual_data$municipality
SE_TYPE <- "stata"

fit_specs <- function(yvar, data) {
  fA <- reformulate("east_river", response = yvar)
  fB <- reformulate(c("east_river", all.vars(ctrl_dem_prop)), response = yvar)
  fC <- reformulate(c("east_river", all.vars(ctrl_dem_prop), all.vars(ctrl_prewar)), response = yvar)
  
  list(
    A = lm_robust(fA, data = data, clusters = municipality, se_type = SE_TYPE),
    B = lm_robust(fB, data = data, clusters = municipality, se_type = SE_TYPE),
    C = lm_robust(fC, data = data, clusters = municipality, se_type = SE_TYPE)
  )
}

coef_labels <- c(
  "east_river"                                   = "East of the river",
  "female"                                       = "Female",
  "age"                                          = "Age",
  "age2"                                         = "Age squared",
  "properties_score"                             = "Prewar property ownership",
  "prewar_family_politician"                     = "Politician",
  "prewar_family_civilservent"                   = "Civil servant",
  "prewar_family_armyofficer"                    = "Army officer",
  "prewar_family_priest"                         = "Priest",
  "prewar_family_tradeunionleader"               = "Trade union leader",
  "(Intercept)"                                  = "Constant"
)

gmap <- data.frame(raw = "nobs", clean = "Observations", fmt = 0, omit = FALSE)

# --------------------------- #
#          TABLE M.1          #
# --------------------------- #

m_left1 <- fit_specs("vote_leftist",            individual_data)  
m_left2 <- fit_specs("leftparty_closeness",     individual_data)  
m_left3 <- fit_specs("left_scale",              individual_data) 

mods_M1 <- list(
  m_left1$A, m_left1$B, m_left1$C,
  m_left2$A, m_left2$B, m_left2$C,
  m_left3$A, m_left3$B, m_left3$C
)

grp_M1 <- list(
  "Voting for leftist parties"           = 1:3,
  "Proximity to leftist parties"         = 4:6,
  "Left-right scale"                     = 7:9
)

TableM1 <- modelsummary(
  mods_M1,
  coef_map   = coef_labels,
  estimate   = "{estimate}{stars}",
  statistic  = "({std.error})",
  stars      = c("**" = .01, "*" = .05, "+" = .10),
  fmt        = 2,
  gof_map    = gmap,
  booktabs   = TRUE,
  title      = "Table M.1: Survey Data — Support for the Left across the Lleida Line",
  notes = list(
    "Standard errors clustered at the municipality level. + p<0.1; * p<0.05; ** p<0.01.",
    "Columns (1), (4), and (7) include no controls.",
    "Columns (2), (5), and (8) include demographic and property controls.",
    "Columns (3), (6), and (9) include all controls, including prewar occupations."
  ),
  grouplabels = grp_M1
)

print(TableM1)

# --------------------------- #
#          TABLE M.2          #
# --------------------------- #

m_nat1 <- fit_specs("vote_catalan",        individual_data)
m_nat2 <- fit_specs("catparty_closeness",  individual_data) 
m_nat3 <- fit_specs("proindy_protest",     individual_data)

mods_M2 <- list(
  m_nat1$A, m_nat1$B, m_nat1$C,
  m_nat2$A, m_nat2$B, m_nat2$C,
  m_nat3$A, m_nat3$B, m_nat3$C
)

grp_M2 <- list(
  "Voting for nationalist parties"               = 1:3,
  "Proximity to nationalist parties"             = 4:6,
  "Nationalist protest behavior"                 = 7:9
)

TableM2 <- modelsummary(
  mods_M2,
  coef_map   = coef_labels,
  estimate   = "{estimate}{stars}",
  statistic  = "({std.error})",
  stars      = c("**" = .01, "*" = .05, "+" = .10),
  fmt        = 2,
  gof_map    = gmap,
  booktabs   = TRUE,
  title      = "Table M.2: Survey Data — Support for Catalan Nationalist Parties & Engagement",
  notes = list(
    "Standard errors clustered at the municipality level. + p<0.1; * p<0.05; ** p<0.01.",
    "Columns (1), (4), and (7) include no controls.",
    "Columns (2), (5), and (8) include demographic and property controls.",
    "Columns (3), (6), and (9) include all controls, including prewar occupations."
  ),
  grouplabels = grp_M2
)

print(TableM2)

# --------------------------- #
# --------------------------- #
#         APPENDIX N          #
# --------------------------- #
# --------------------------- #

individual_data <- individual_data %>%
  mutate(
    age_grp = ifelse(age <= 69, "Below 69", "Above 69")
  )


fit_by_age <- function(y, data) {
  fml <- as.formula(paste(
    y, "~ east_river + female + properties_score +",
    "prewar_family_politician + prewar_family_civilservent +",
    "prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader"
  ))
  
  list(
    below69 = lm_robust(fml, data = data[data$age_grp == "Below 69", ],
                        clusters = municipality, se_type = "stata"),
    above69 = lm_robust(fml, data = data[data$age_grp == "Above 69", ],
                        clusters = municipality, se_type = "stata")
  )
}

m_vote    <- fit_by_age("vote_catalan",       individual_data)
m_prox    <- fit_by_age("catparty_closeness", individual_data)
m_protest <- fit_by_age("proindy_protest",    individual_data)

mods_N1 <- list(
  m_vote$below69,    m_vote$above69,
  m_prox$below69,    m_prox$above69,
  m_protest$below69, m_protest$above69
)

coef_map <- c("east_river" = "East of the river")
gmap <- data.frame(raw = "nobs", clean = "Observations", fmt = 0, omit = FALSE)

grp_headers <- list(
  "Voting for\nCatalan nationalist\nparties"      = 1:2,
  "Proximity to\nCatalan nationalist\nparties"     = 3:4,
  "Catalan nationalist\nprotest behavior"         = 5:6
)

colnames_override <- c("Below 69", "Above 69",
                       "Below 69", "Above 69",
                       "Below 69", "Above 69")

TableN1 <- modelsummary(
  mods_N1,
  coef_map   = coef_map,
  estimate   = "{estimate}{stars}",
  statistic  = "({std.error})",
  stars      = c("**" = .01, "*" = .05, "+" = .10),
  gof_map    = gmap,
  fmt        = 2,
  booktabs   = TRUE,
  title      = "Table N.1: Differences in Support for Catalan Nationalism across Age Groups",
  notes = list(
    "+ p<0.1; * p<0.05; ** p<0.01. Higher values indicate greater support for Catalan nationalism.",
    "Standard errors (clustered by municipality) in parentheses. Control variables include gender, property ownership, and prewar relatives’ occupations, omitted here for brevity."
  ),
  grouplabels = grp_headers
)

print(TableN1)

# --------------------------- #
# --------------------------- #
#         APPENDIX O          #
# --------------------------- #
# --------------------------- #

lower_lat <- 40.9
upper_lat <- 41.3

individual_data_noebro <- individual_data[
  which(as.numeric(individual_data$centroid_lat) < lower_lat |
          as.numeric(individual_data$centroid_lat) > upper_lat),
]

# --------------------------- #
#   APPENDIX O.2: TABLE O.2   #
# --------------------------- #

rows_noebro <- list(
  "Death of relatives" = list(
    all = individual_data_noebro$deaths,
    nat = individual_data_noebro$deaths_nat,
    rep = individual_data_noebro$deaths_rep
  ),
  "Bodily harm" = list(
    all = individual_data_noebro$bodilyharm,
    nat = individual_data_noebro$bodilyharm_nat,
    rep = individual_data_noebro$bodilyharm_rep
  ),
  "Imprisonment" = list(
    all = individual_data_noebro$imprisonment,
    nat = individual_data_noebro$imprisonment_nat,
    rep = individual_data_noebro$imprisonment_rep
  ),
  "Property damage" = list(
    all = individual_data_noebro$materialdamage,
    nat = individual_data_noebro$materialdamage_nat,
    rep = individual_data_noebro$materialdamage_rep
  ),
  "Fleeing home" = list(
    all = individual_data_noebro$leaving,
    nat = individual_data_noebro$leaving_nat,
    rep = individual_data_noebro$leaving_rep
  )
)

TableO2 <- purrr::imap_dfr(
  rows_noebro,
  function(vars, label) {
    c_all <- west_east_t(vars$all, individual_data_noebro$east_river)
    c_nat <- west_east_t(vars$nat, individual_data_noebro$east_river)
    c_rep <- west_east_t(vars$rep, individual_data_noebro$east_river)
    tibble::tibble(
      Outcome = label,
      `All violence, West`            = c_all$West,
      `All violence, East`            = c_all$East,
      `All violence, t-stat`          = c_all$tstat,
      `Nationalist violence, West`    = c_nat$West,
      `Nationalist violence, East`    = c_nat$East,
      `Nationalist violence, t-stat`  = c_nat$tstat,
      `Republican violence, West`     = c_rep$West,
      `Republican violence, East`     = c_rep$East,
      `Republican violence, t-stat`   = c_rep$tstat
    )
  }
)

print(TableO2)

# --------------------------- #
#   APPENDIX O.4: TABLE O.3   #
# --------------------------- #

t4m1_noEbro <- lm_robust(
  vote_leftist ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data_noebro, clusters = municipality, se_type = "stata"
)

t4m2_noEbro <- lm_robust(
  leftparty_closeness ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data_noebro, clusters = municipality, se_type = "stata"
)

t4m3_noEbro <- lm_robust(
  left_scale ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data_noebro, clusters = municipality, se_type = "stata"
)

t4m4_noEbro <- lm_robust(
  vote_catalan ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data_noebro, clusters = municipality, se_type = "stata"
)

t4m5_noEbro <- lm_robust(
  catparty_closeness ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data_noebro, clusters = municipality, se_type = "stata"
)

t4m6_noEbro <- lm_robust(
  proindy_protest ~ east_river + female + age + age2 +
    properties_score + prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest + prewar_family_tradeunionleader,
  data = individual_data_noebro, clusters = municipality, se_type = "stata"
)

models_noEbro <- list(
  "Voting for leftist parties"                 = t4m1_noEbro,
  "Proximity to leftist parties"               = t4m2_noEbro,
  "Left-right scale"                           = t4m3_noEbro,
  "Voting for Catalan nationalist parties"     = t4m4_noEbro,
  "Proximity to Catalan nationalist parties"   = t4m5_noEbro,
  "Catalan nationalist protest behavior"       = t4m6_noEbro
)

coef_labels <- c(
  "east_river"                     = "East of the river",
  "female"                         = "Female",
  "age"                            = "Age",
  "age2"                           = "Age squared",
  "properties_score"               = "Prewar property ownership",
  "prewar_family_politician"       = "Politician",
  "prewar_family_civilservent"     = "Civil servant",
  "prewar_family_armyofficer"      = "Army officer",
  "prewar_family_priest"           = "Priest",
  "prewar_family_tradeunionleader" = "Trade union leader",
  "(Intercept)"                    = "Constant"
)

gmap <- data.frame(
  raw   = "nobs",
  clean = "Observations",
  fmt   = 0,
  omit  = FALSE
)

TableO3 <- modelsummary(
  models_noEbro,
  coef_map  = coef_labels,   # show all controls
  estimate  = "{estimate}{stars}",
  statistic = "({std.error})",
  gof_map   = gmap,
  stars     = c("**" = .01, "*" = .05, "+" = .10),
  booktabs  = TRUE,
  fmt = 2,
  title = "Table O.3: Support for the Left and Catalan Nationalism across the Lleida Line (No Ebro Towns, All Controls)",
  notes = list(
    "+ p<0.1; * p<0.05; ** p<0.01.",
    "Control variables include gender, age, age squared, property ownership, and relatives’ prewar occupations.",
    "Standard errors are clustered at the municipality level.",
    "Ebro towns excluded using latitude filter."
  )
)

print(TableO3)


# --------------------------- #
# --------------------------- #
#         APPENDIX P          #
# --------------------------- #
# --------------------------- #

# --------------------------- #
#  APPENDIX P.2.1: TABLE P.2  #
# --------------------------- #

data_12km <- individual_data %>%
  filter(!is.na(dist_river_combined), dist_river_combined <= 12)

m1_12km <- lm_robust(
  vote_leftist ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_12km, clusters = municipality, se_type = "stata"
)

m2_12km <- lm_robust(
  leftparty_closeness ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_12km, clusters = municipality, se_type = "stata"
)

m3_12km <- lm_robust(
  left_scale ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_12km, clusters = municipality, se_type = "stata"
)

m4_12km <- lm_robust(
  vote_catalan ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_12km, clusters = municipality, se_type = "stata"
)

m5_12km <- lm_robust(
  catparty_closeness ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_12km, clusters = municipality, se_type = "stata"
)

m6_12km <- lm_robust(
  proindy_protest ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_12km, clusters = municipality, se_type = "stata"
)

coef_labels <- c(
  "east_river" = "East of the river"
)

gmap <- data.frame(raw = "nobs", clean = "Observations", fmt = 0, omit = FALSE)

Table_P2 <- modelsummary(
  list(m1_12km, m2_12km, m3_12km, m4_12km, m5_12km, m6_12km),
  coef_map  = coef_labels,
  estimate  = "{estimate}{stars}",
  statistic = "({std.error})",
  stars     = c("**" = .01, "*" = .05, "+" = .10),
  fmt       = 2,
  gof_map   = gmap,
  booktabs  = TRUE,
  title     = "Table P.2: Differences in political attitudes and behaviors across the river border after restricting the sample to those who reside within 12km of the line",
  notes     = list(
    "+p<0.1; *p<0.05; **p<0.01. Dependent variables are recoded to ensure that greater values indicate more leftist positions in columns 1–3, and more Catalan pro-independence positions in columns 4–6. Standard errors clustered at municipality level. All controls include individual-level covariates, pre-treatment violence measures, and all pre-war municipality-level controls (population, associationalism, electoral behavior)."
  )
)

print(Table_P2)


# --------------------------- #
#  APPENDIX P.2.2: TABLE P.3  #
# --------------------------- #

data_7km <- individual_data %>%
  filter(!is.na(dist_river_combined), dist_river_combined <= 7)

m1_7km <- lm_robust(
  vote_leftist ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_7km, clusters = municipality, se_type = "stata"
)

m2_7km <- lm_robust(
  leftparty_closeness ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_7km, clusters = municipality, se_type = "stata"
)

m3_7km <- lm_robust(
  left_scale ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_7km, clusters = municipality, se_type = "stata"
)

m4_7km <- lm_robust(
  vote_catalan ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_7km, clusters = municipality, se_type = "stata"
)

m5_7km <- lm_robust(
  catparty_closeness ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_7km, clusters = municipality, se_type = "stata"
)

m6_7km <- lm_robust(
  proindy_protest ~ east_river + female + age + I(age^2) + properties_score +
    prewar_family_politician + prewar_family_civilservent +
    prewar_family_armyofficer + prewar_family_priest +
    prewar_family_tradeunionleader,
  data = data_7km, clusters = municipality, se_type = "stata"
)

coef_labels <- c(
  "east_river" = "East of the river"
)

gmap <- data.frame(raw = "nobs", clean = "Observations", fmt = 0, omit = FALSE)

Table_P3 <- modelsummary(
  list(m1_7km, m2_7km, m3_7km, m4_7km, m5_7km, m6_7km),
  coef_map  = coef_labels,
  estimate  = "{estimate}{stars}",
  statistic = "({std.error})",
  stars     = c("**" = .01, "*" = .05, "+" = .10),
  fmt       = 2,
  gof_map   = gmap,
  booktabs  = TRUE,
  title     = "Table P.2: Differences in political attitudes and behaviors across the river border after restricting the sample to those who reside within 12km of the line",
  notes     = list(
    "+p<0.1; *p<0.05; **p<0.01. Dependent variables are recoded to ensure that greater values indicate more leftist positions in columns 1–3, and more Catalan pro-independence positions in columns 4–6. Standard errors clustered at municipality level. All controls include individual-level covariates, pre-treatment violence measures, and all pre-war municipality-level controls (population, associationalism, electoral behavior)."
  )
)

print(Table_P3)

# --------------------------- #
# --------------------------- #
#         APPENDIX Q          #
# --------------------------- #
# --------------------------- #

# --------------------------- #
#         APPENDIX Q.1        #
# --------------------------- #

m1 <- lm_robust(
  deaths ~ fam_supp_nat_vs_rep,
  data = individual_data, clusters = municipality, se_type = "stata"
)

m2 <- lm_robust(
  deaths ~ fam_supp_nat,
  data = individual_data, clusters = municipality, se_type = "stata"
)

m3 <- lm_robust(
  deaths ~ fam_supp_rep,
  data = individual_data, clusters = municipality, se_type = "stata"
)

coef_map <- c(
  "fam_supp_nat_vs_rep" = "Support for Nationalists vs. Republicans",
  "fam_supp_nat"     = "Family supported Nationalists (binary)",
  "fam_supp_rep"     = "Family supported Republicans (binary)",
  "(Intercept)"          = "Constant"
)

gmap <- data.frame(raw = "nobs", clean = "Observations", fmt = 0, omit = FALSE)

TableQ1 <- modelsummary(
  list(m1, m2, m3),
  coef_map  = coef_map,
  estimate  = "{estimate}{stars}",
  statistic = "({std.error})",
  stars     = c("**" = .01, "*" = .05, "+" = .10),
  fmt       = 3,
  booktabs  = TRUE,
  title     = "DV: Family member killed due to the war",
  gof_map   = gmap,
  notes = list(
    "Clustered standard errors by municipality in parentheses.  +p<0.1; *p<0.05; **p<0.01."
  )
)

print(TableQ1)

# --------------------------- #
#         APPENDIX Q.3        #
# --------------------------- #

m1 <- lm_robust(
  east_river ~ catalan_home,
  data = individual_data,
  clusters = municipality, se_type = "stata"
)

m2 <- lm_robust(
  east_river ~ catalan_home + both_home,
  data = individual_data,
  clusters = municipality, se_type = "stata"
)

coef_map <- c(
  "catalan_home" = "Catalan spoken at home (Yes=1)",
  "both_home"    = "Both languages spoken at home equally (Yes=1)",
  "(Intercept)"  = "Constant"
)

gmap <- data.frame(raw = "nobs", clean = "Observations", fmt = 0, omit = FALSE)

TableQ3 <- modelsummary(
  list(m1, m2),
  coef_map  = coef_map,
  estimate  = "{estimate}{stars}",
  statistic = "({std.error})",
  stars     = c("**" = .01, "*" = .05, "+" = .10),
  fmt       = 3,
  booktabs  = TRUE,
  gof_map   = gmap,
  title     = "DV: East of River = 1",
  notes     = list("Clustered standard errors by municipality in parentheses.  +p<0.1; *p<0.05; **p<0.01.")
)

print(TableQ3)

# --------------------------- #
# --------------------------- #
#         APPENDIX R          #
# --------------------------- #
# --------------------------- #

# --------------------------- #
#   APPENDIX R.2: TABLE R.1   #
# --------------------------- #

m_fig3 <- lm_robust(
  out ~ as.factor(catalan_name) + as.factor(age) + as.factor(edu) +
    as.factor(birth) + as.factor(econ) + as.factor(terri),
  data = conjoint_data, clusters = id, se_type = "stata"
)

order_terms <- c(
  "hdr_lr",
  "as.factor(econ)2",
  "hdr_terr",
  "as.factor(terri)2",
  "hdr_name",
  "as.factor(catalan_name)1",
  "hdr_age",
  "as.factor(age)27","as.factor(age)30","as.factor(age)32",
  "as.factor(age)34","as.factor(age)39","as.factor(age)45",
  "hdr_edu",
  "as.factor(edu)2","as.factor(edu)3","as.factor(edu)4",
  "hdr_birth",
  "as.factor(birth)1","as.factor(birth)3","as.factor(birth)4",
  "(Intercept)"
)

label_map <- c(
  "hdr_lr"                    = "Left–right preferences:",
  "as.factor(econ)2"          = "Socialist",
  "hdr_terr"                  = "Center–periphery preferences:",
  "as.factor(terri)2"         = "Separatist",
  "hdr_name"                  = "Name origin:",
  "as.factor(catalan_name)1"  = "Catalan name",
  "hdr_age"                   = "Age:",
  "as.factor(age)27"          = "27",
  "as.factor(age)30"          = "30",
  "as.factor(age)32"          = "32",
  "as.factor(age)34"          = "34",
  "as.factor(age)39"          = "39",
  "as.factor(age)45"          = "45",
  "hdr_edu"                   = "Education:",
  "as.factor(edu)2"           = "Primary school",
  "as.factor(edu)3"           = "Secondary school",
  "as.factor(edu)4"           = "College degree",
  "hdr_birth"                 = "Birthplace province:",
  "as.factor(birth)1"         = "Girona",
  "as.factor(birth)3"         = "Tarragona",
  "as.factor(birth)4"         = "Lleida",
  "(Intercept)"               = "Constant"
)

star <- function(p) ifelse(is.na(p), "", ifelse(p < .01, "**", ifelse(p < .05, "*", ifelse(p < .10, "+", ""))))

tid <- tidy(m_fig3) %>%
  select(term, estimate, std.error, p.value)

heads <- tibble(
  term      = c("hdr_lr","hdr_terr","hdr_name","hdr_age","hdr_edu","hdr_birth"),
  estimate  = NA_real_, std.error = NA_real_, p.value = NA_real_
)

tid2 <- bind_rows(tid, heads) %>%
  filter(term %in% order_terms) %>%
  mutate(term = factor(term, levels = order_terms)) %>%
  arrange(term) %>%
  mutate(
    label = label_map[as.character(term)],
    est_star = ifelse(is.na(estimate), "", sprintf("%.3f%s", estimate, star(p.value))),
    se_line  = ifelse(is.na(std.error), "", sprintf("(%.3f)", std.error)),
    is_header = grepl("^hdr_", as.character(term))
  )

tab_rows <- tid2 %>%
  mutate(
    LabelOut = case_when(
      label == "Left–right preferences:"           ~ "Left–right preferences:",
      label == "Center–periphery preferences:"     ~ "Center-periphery preferences:",
      label == "Name origin:"                      ~ "Name origin:",
      label == "Age:"                              ~ "Age:",
      label == "Education:"                        ~ "Education:",
      label == "Birthplace province:"              ~ "Birthplace province:",
      TRUE ~ label
    )
  ) %>%
  select(LabelOut, est_star, se_line, is_header)

ref_block <- tibble(
  LabelOut = c("Conservative (ref)", "",  # under LR prefs
               "Unionist (ref)",    "",  # under center-periphery
               "Spanish name (ref)", "",  # name origin
               "23 (ref)",          "",  # age
               "Illiterate (ref)",  "",  # education
               "Barcelona (ref)",   ""   # birthplace
  ),
  est_star = "", se_line = "", is_header = FALSE
)

insert_after <- function(tbl, header_label, extra) {
  idx <- which(tbl$LabelOut == header_label & tbl$is_header)
  if (length(idx) == 0) return(tbl)
  bind_rows(
    tbl[1:idx, ],
    tibble(LabelOut = "", est_star = "", se_line = "", is_header = FALSE), # spacer
    extra,
    tbl[(idx+1):nrow(tbl), ]
  )
}

tab <- tab_rows

tab$LabelOut[tab$is_header] <- paste0("\\textit{", tab$LabelOut[tab$is_header], "}")

tab <- insert_after(tab, "\\textit{Left–right preferences:}",
                    ref_block[1:2, ])
tab <- insert_after(tab, "\\textit{Center-periphery preferences:}",
                    ref_block[3:4, ])
tab <- insert_after(tab, "\\textit{Name origin:}",
                    ref_block[5:6, ])
tab <- insert_after(tab, "\\textit{Age:}",
                    ref_block[7:8, ])
tab <- insert_after(tab, "\\textit{Education:}",
                    ref_block[9:10, ])
tab <- insert_after(tab, "\\textit{Birthplace province:}",
                    ref_block[11:12, ])

tab$is_header <- NULL

const <- tid %>% filter(term == "(Intercept)") %>%
  transmute(LabelOut = "Constant",
            est_star = sprintf("%.3f%s", estimate, star(p.value)),
            se_line  = sprintf("(%.3f)", std.error))

obs   <- glance(m_fig3)$nobs

TableR1 <- bind_rows(tab,
                       tibble(LabelOut = "", est_star = "", se_line = ""),
                       const,
                       tibble(LabelOut = "Observations", est_star = as.character(obs), se_line = ""))


print(TableR1)

# --------------------------- #
#  APPENDIX R.3: Figure R.1   #
# --------------------------- #

conjoint_west <- lm_robust(out ~ as.factor(catalan_name) + as.factor(age) + as.factor(edu) + as.factor(birth) + as.factor(econ) + as.factor(terri),
                                   data=conjoint_data[conjoint_data$east_river == 0, ], clusters=id, se_type="stata")

conjoint_east <- lm_robust(out ~ as.factor(catalan_name) + as.factor(age) + as.factor(edu) + as.factor(birth) + as.factor(econ) + as.factor(terri),
                                   data=conjoint_data[conjoint_data$east_river == 1, ], clusters=id, se_type="stata")

tid_east <- tidy(conjoint_east)[2:16,]
tid_east$outcome <- "east"
tid_west <- tidy(conjoint_west)[2:16,]
tid_west$outcome <- "west"

tid_both <- bind_rows(tid_east, tid_west)

new_row <- data.frame(
  term = c("Barcelona", "Birthplace province:",  "Illiterate (ref.)", "Education:", "Age:", "23 (ref.)", 
           "Center−periphery \n preferences:", "Unionist (ref.)", "Left-Right preferences:", "Conservative (ref.)", 
           "Name origin:", "spanish_name (ref.)", "Space1", "Space2", "Space3", "Space4", "Space5", "Space6"),
  estimate = c(0,NA,0,NA,NA,0,NA,0,NA,0,NA,0,NA,NA,NA,NA,NA,NA),
  std.error = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  statistic = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  p.value = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  conf.low = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  conf.high = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  df = c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
  outcome = c("east", "east", "east", "east", "east", 
              "east", "east", "east", "east",
              "west", "west","west", "west", "west", "west", "west", 
              "west", "west")
)

tid_both <- rbind(new_row, as.data.frame(tid_both))

label_map <- c(
  "Left-Right preferences:" = "Left-right preferences:",
  "Conservative (ref.)" = "Conservative (ref.)",
  "as.factor(econ)2" = "Socialist",
  "Center−periphery \n preferences:" = "Center−periphery preferences:",
  "Unionist (ref.)" = "Unionist (ref.)",
  "as.factor(terri)2" = "Separatist",
  "Name origin:" = "Name origin:",
  "spanish_name (ref.)" = "Spanish name (ref.)",
  "as.factor(catalan_name)1" = "Catalan name",
  "Age:" = "Age:",
  "23 (ref.)" = "23 (ref.)",
  "as.factor(age)27" = "27",
  "as.factor(age)30" = "30",
  "as.factor(age)32" = "32",
  "as.factor(age)34" = "34",
  "as.factor(age)39" = "39",
  "as.factor(age)45" = "45",
  "Education:" = "Education:",
  "Illiterate (ref.)" = "Illiterate (ref.)", 
  "as.factor(edu)4" = "College degree",
  "as.factor(edu)2" = "Secondary school",
  "as.factor(edu)3" = "Primary school",
  "Birthplace province:" = "Birthplace province:",
  "Barcelona" = "Barcelona (ref.)",
  "as.factor(birth)1" = "Lleida",
  "as.factor(birth)3" = "Girona",
  "as.factor(birth)4" = "Tarragona",
  "Space1" = " ",
  "Space2" = "  ", 
  "Space3" = "   ", 
  "Space4" = "    ", 
  "Space5" = "     ", 
  "Space6" = "      "
)

tid_both$term <- label_map[tid_both$term]

attribute_order <- c("Lleida", "Girona", "Tarragona", "Barcelona (ref.)", 
                     "Birthplace province:", " ", 
                     "College degree", "Secondary school", "Primary school", "Illiterate (ref.)",
                     "Education:", "  ", 
                     "45", "39", "34", "32", "30", "27", "23 (ref.)",
                     "Age:", "   ", 
                     "Catalan name", "Spanish name (ref.)",
                     "Name origin:", "    ", 
                     "Separatist", "Unionist (ref.)",
                     "Center−periphery preferences:", "     ", 
                     "Socialist", "Conservative (ref.)",
                     "Left-right preferences:", "      ")


dodge_width <- 1

FigureR1 <- ggplot(tid_both, aes(x = factor(term, levels = attribute_order), y = estimate, color = outcome)) +
  geom_point(aes(alpha = case_when(
    term %in% c("Name origin:", "Left-right preferences:", "Center−periphery preferences:", "Age:", "Education:", "Birthplace province:") ~ 0,
    TRUE ~ 1
  )), position = position_dodge(width = dodge_width), size = 3) +
  geom_errorbar(aes(ymin = estimate - std.error, ymax = estimate + std.error),
                position = position_dodge(width = dodge_width), width = 0.2, size = 1) +
  scale_x_discrete(labels = c("Lleida", "Girona", "Tarragona", "Barcelona (ref.)", 
                              expression(bold("Birthplace province:")), " ", 
                              "College degree", "Secondary school", "Primary school", "Illiterate (ref.)",
                              expression(bold("Education:")), "  ", 
                              "45", "39", "34", "32", "30", "27", "23 (ref.)",
                              expression(bold("Age:")), "   ", 
                              "Catalan name", "Spanish name (ref.)",
                              expression(bold("Name origin:")), "    ", 
                              "Separatist", "Unionist (ref.)",
                              expression(bold("Center−periphery preferences:")), "     ", 
                              "Socialist", "Conservative (ref.)",
                              expression(bold("Left-right preferences:")))) +
  coord_flip() +
  geom_hline(yintercept = 0, alpha = 0.5, color = "gray90", linetype = "solid") +
  theme_minimal() +
  theme(
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank(),  
    panel.background = element_blank(),
    axis.title.x = element_text(face = "bold")
  ) +
  labs(x = "", y = "Effect on Pr(Combatant of the Republican Army)", title = "") +
  scale_color_manual(values = c("east" = "blue", "west" = "red"), labels = c("East of the river", "West of the river")) +
  guides(color = guide_legend(title = "River bank:"), alpha = "none")


print(FigureR1)

